package com.gxa.global.jwt;

import com.alibaba.fastjson.JSONObject;
import com.gxa.common.JwtResult;
import com.gxa.common.Result;
import com.gxa.utils.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {
    /**
     * 在进入控制器之前执行
     * 如果是返回false就阻止控制器执行
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String token = httpServletRequest.getHeader("Authorization");
        //设置响应的类型为json
        httpServletResponse.setContentType("application/json;charset=utf-8");
        Result r = new Result();
        if (token == null || "".equals(token)) {
            r.setCode(500);
            r.setMsg("请登录");
            httpServletResponse.getWriter().write(JSONObject.toJSONString(r));
            httpServletResponse.getWriter().flush();
            httpServletResponse.getWriter().close();
            return false;
        }
        JwtResult jwtResult = JwtUtils.validateJwt(token);
        if (jwtResult.isSuccess()){
            // 验证通过
            return true;
        }else {
            r.setCode(jwtResult.getErrCode());
            r.setMsg("验证不通过请重新登录！");
            httpServletResponse.getWriter().write(JSONObject.toJSONString(r));
            httpServletResponse.getWriter().flush();
            httpServletResponse.getWriter().close();
            return false;
        }
    }


    /**
     * 控制器执行完成，进入到jsp之前
     * 作用：
     *   日志记录
     *   敏感词语过滤
     * */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在整个jsp成之后执行，
     * 作用：记录过程中出现的异常，可以记录到日志文件中。
     * */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
